package com.example.authsystem.security;

import com.example.authsystem.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器
 * 继承OncePerRequestFilter确保每个请求只经过一次该过滤器
 * 用于从请求中提取JWT令牌，验证其有效性，并将验证通过的用户信息设置到Spring Security的上下文中
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    /**
     * JWT令牌工具类，提供令牌的生成、解析和验证功能
     */
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 用户详情服务，用于根据用户名加载用户信息
     */
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 过滤请求，验证JWT令牌并设置认证信息
     * 该方法是过滤器的核心实现，由Spring Security自动调用
     * 
     * @param request HTTP请求对象，用于获取请求头中的JWT令牌
     * @param response HTTP响应对象，目前未使用，但必须保留在方法签名中
     * @param filterChain 过滤器链，用于将请求传递给下一个过滤器
     * @throws ServletException 当发生Servlet异常时抛出
     * @throws IOException 当发生IO异常时抛出
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        // 从请求头中获取Authorization字段
        final String requestTokenHeader = request.getHeader("Authorization");

        String username = null;
        String jwtToken = null;

        // JWT令牌格式为"Bearer token"，需要去除Bearer前缀获取实际令牌
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            try {
                // 从令牌中提取用户名
                username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            } catch (Exception e) {
                logger.warn("JWT Token has expired or is invalid");
            }
        } else {
            logger.warn("JWT Token does not begin with Bearer String");
        }

        // 如果令牌中提取到了用户名，且当前没有已认证的用户，则继续验证
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            // 加载用户详情信息
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            // 验证令牌是否有效
            if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {

                // 创建认证对象，包含用户信息和权限
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = 
                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                // 设置认证详情，如IP地址等
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // 将认证对象设置到Spring Security上下文中，表明当前用户已通过认证
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        // 继续过滤器链，将请求传递给下一个过滤器
        filterChain.doFilter(request, response);
    }
}